//console.log('background.js');
const baseUrl = 'http://api.yi-ja.com/';
const apps = chrome.app.getDetails();

console.log(
    `%c ${apps.name} %c Version:${apps.version} %c`,
    'background:#35495e; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
    'background:#41b883; padding: 1px; border-radius: 0 3px 3px 0;  color: #fff',
    'background:transparent;'
);

// 监听网页消息
chrome.runtime.onMessageExternal.addListener(function (request, sender, sendResponse) {
    // 可以针对sender做一些白名单检查
    console.log('listener message', request.type);
    // 登录
    if (request.type == 'login') {
        let data = request.data;
        localStorage.setItem('token', data);
        initContentMenus();
        sendResponse({type: 'login_success', msg: '插件账户登录成功'});
    }
    // 设置信息
    else if (request.type == 'key') {
        let data = request.data;
        localStorage.setItem('key', data);
    }
    // 设置key
    else if (request.type == 'info') {
        let data = request.data;
        localStorage.setItem('info', JSON.stringify(data));
    }
    // 退出
    else if (request.type == 'out') {
        clearStorage();
        clearContentMenus();
        sendResponse({type: 'out_success', msg: '插件账户退出成功'});
    }
});

// 通知消息
function notice(msg, title) {
    chrome.notifications.create(null, {
        type: 'basic',
        iconUrl: 'logo.png',
        title: title || '提醒',
        message: msg || '提示消息',
    });
}

// 设置登录缓存
function setLoginStorage(token, key, info) {
    localStorage.setItem('token', token);
    localStorage.setItem('key', key);
    localStorage.setItem('info', JSON.stringify(info));
}

// 获取key
function getKey() {
    return localStorage.getItem('key') || '';
}

// 获取token
function getToken() {
    return localStorage.getItem('token') || '';
}

// 清理token
function clearStorage() {
    localStorage.clear();
}

// 获取分类菜单
function getEngine(call) {
    // 发送请求
    axios({
        method: 'get',
        url: baseUrl + 'nav/engine',
        params: {
            key: getKey()
        }
    }).then(rps => {
        let res = rps.data,
            code = res.code,
            msg = res.msg;
        if (code == 0) {
            let list = res.list;
            call && call(list);
        }
    }).catch(err => {
        console.log(err);
    });
}

// 获取分类
function getMenu(call) {
    // 发送请求
    axios({
        method: 'get',
        url: baseUrl + 'nav/menu',
        params: {
            key: getKey()
        }
    }).then(rps => {
        let res = rps.data,
            code = res.code,
            msg = res.msg;
        if (code == 0) {
            let list = res.list;
            call && call(list);
        }
    }).catch(err => {
        console.log(err);
    });
}

// 保存网页(添加书签)
function addBookmark(data) {
    let that = this;
    // 发送请求
    axios({
        method: 'post',
        url: baseUrl + 'nav/addBookmark',
        data: 'token=' + data.token + '&mid=' + data.mid + '&title=' + data.title + '&url=' + data.url
    }).then(rps => {
        let res = rps.data,
            code = res.code,
            msg = res.msg;
        that.notice(msg);
        // 登录失效
        if (code == 999) {
            clearStorage();
            clearContentMenus();
        }
    }).catch(err => {
        console.log(err);
    });
}

// 右键菜单清空
function clearContentMenus() {
    console.log('clearContentMenus');
    chrome.contextMenus.removeAll();
}

// 右键菜单初始化
function initContentMenus() {
    console.log('initContentMenus');
    // 获取引擎,创建搜索右键菜单
    getEngine((list) => {
        list.forEach(item => {
            chrome.contextMenus.create({
                title: '使用 "' + item.title + '" 搜索：%s',
                contexts: ["selection"],
                onclick: function (params) {
                    chrome.tabs.create({url: item.url + encodeURI(params.selectionText)});
                }
            })
        })
    });
    // 获取分类,创建网页收藏至分类右键菜单
    getMenu((list) => {
        list.forEach(item => {
            chrome.contextMenus.create({
                title: '添加至 "' + item.title + '"',
                contexts: ["page"],
                onclick: function (info, tab) {
                    console.log('add bookmark to menu', info, tab);
                    let data = {
                        mid: item.id,
                        title: tab.title || '',
                        url: tab.url || '',
                        token: getToken(),
                    };
                    addBookmark(data);
                }
            })
        })
    });
}
